package cn.tangwei.order.service.impl;

import cn.tangwei.basic.service.impl.BaseServiceImpl;
import cn.tangwei.basic.utils.CodeGenerateUtils;
import cn.tangwei.basic.utils.PageList;
import cn.tangwei.order.constants.OrderConstants;
import cn.tangwei.order.domain.AdoptOrder;
import cn.tangwei.order.domain.OrderAddress;
import cn.tangwei.order.mapper.AdoptOrderMapper;
import cn.tangwei.order.mapper.OrderAddressMapper;
import cn.tangwei.order.query.AdoptOrderQuery;
import cn.tangwei.order.service.IAdoptOrderService;
import cn.tangwei.org.domain.Employee;
import cn.tangwei.org.mapper.EmployeeMapper;
import cn.tangwei.pay.constants.PayConstants;
import cn.tangwei.pay.domain.PayBill;
import cn.tangwei.pay.mapper.PayBillMapper;
import cn.tangwei.pay.service.IPayBillService;
import cn.tangwei.pet.domain.Pet;
import cn.tangwei.pet.mapper.PetMapper;
import cn.tangwei.pet.mapper.SearchMasterMsgMapper;
import cn.tangwei.quartz.constans.JobTypes;
import cn.tangwei.quartz.service.IQuartzService;
import cn.tangwei.quartz.utils.QuartzJobInfo;
import cn.tangwei.user.domain.LoginInfo;
import cn.tangwei.user.domain.User;
import cn.tangwei.user.domain.UserAddress;
import cn.tangwei.user.mapper.UserAddressMapper;
import cn.tangwei.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private AdoptOrderMapper adoptOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;




    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, LoginInfo loginInfo) {
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        if(employee.getShop_id() != null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, LoginInfo loginInfo) {
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public String submit(Map<String, Object> map, LoginInfo loginInfo) {
        // 1.参数校验
        Integer serviceMethod = Integer.valueOf(map.get("service_method").toString());// 送货方式
        Long addressId = Long.valueOf(map.get("address_id").toString());// 收货地址
        Long payMethod = Long.valueOf(map.get("pay_method").toString());// 支付方式
        Long petId = Long.valueOf(map.get("pet_id").toString());// 宠物id
        // 2.修改宠物状态+下架时间+绑定领养人
        // 修改消息状态
        Pet pet = petMapper.queryById(petId);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        pet.setUser_id(user.getId());
        pet.setOffsaletime(new Date());
        pet.setState(0);
        petMapper.update(pet);
        // 3.创建领养订单，订单本表
        AdoptOrder order = initAdoptOrder(pet, user);
        // 为了后面生成支付订单不用再修改订单了，先生成统一支付标识，后面直接拿
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        adoptOrderMapper.save(order); //返回自增ID
        // 订单地址表
        UserAddress userAddress = userAddressMapper.queryById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        // 4.支付订单并支付
        PayBill bill = initPayBill(payMethod, user, order);
        payBillMapper.save(bill);
        //@TODO 5.超时未支付自动取消
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        jobInfo.setJobName(JobTypes.PAY_OVER_TIME_ADOPT_ORDER + order.getId());
        Map<String, Object> maps = new HashMap<>();
        maps.put("type", JobTypes.PAY_OVER_TIME_ADOPT_ORDER);
        maps.put("orderId", order.getId());
        jobInfo.setParams(maps);
        jobInfo.setFireDate(order.getLastPayTime());// 15分钟超时取消
        quartzService.addJob(jobInfo);

        // 封装的统一支付接口
        return payBillService.pay(bill);
    }

    @Override
    public void deleteByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.queryById(orderId);
        if(adoptOrder.getState() == 0){
            adoptOrder.setState(-1);
            adoptOrderMapper.update(adoptOrder);
            System.out.println("quartz触发执行取消订单" + orderId);
        }
    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());
        bill.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);// 领养订单类型
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setUser_id(user.getId());
        order.setPet_id(pet.getId());
        order.setShop_id(pet.getShop_id());
        order.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));//支付超时自动取消
        return order;
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }
}
